<?php


namespace app\beautiful\controller\admin\finance;


use app\BaseController;
use app\beautiful\model\finance\AccountBalanceModel;
use app\beautiful\model\finance\WithdrawAccountLogModel;
use app\beautiful\model\finance\WithdrawAccountModel;
use app\beautiful\model\finance\WithdrawModel;
use app\common\logic\DataLogic;
use app\common\model\DataConfigModel;
use app\common\model\ShopBalanceLogsModel;
use think\facade\Db;


class Withdraw extends BaseController
{
    /*获取提现页面*/
    public function withdrawInfo(){
        $type = $this->request->param('type/d',1);//1账户提现2分佣提现
        if(!in_array($type,[1,2])) return $this->error('类型有误');
        //获取默认账户
        $account = WithdrawAccountModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'is_default'=>1])->find();
        $balance = AccountBalanceModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        $return =$account;
        $return['account_money'] = $type == 1?$balance->account_money:$balance->lock_money;
        //获取余额

        //手续费
        $config = DataConfigModel::where('1=1')->find();
        $return['lock_settle_ratio'] = $config?$config->lock_settle_ratio:0;
        $return['settle_ratio'] = $config?$config->settle_ratio:0;
        return $this->success($return);
    }
    /*提现申请*/
    public function applyFor(){
        $type = $this->request->param('type/f',1);//1账户提现2分佣提现
        $money = $this->request->param('money/f',0);
        $withdraw_account_id = $this->request->param('withdraw_account_id/d',0);
        if(!in_array($type,[1,2])) return $this->error('提现类型有误');
        if($money<1){
            return $this->error('提现金额必须大于0');
        }
        if(null === $withdraw_account = WithdrawAccountModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'withdraw_account_id'=>$withdraw_account_id])->find()){
            return $this->error('提现账户不存在');
        }
        if(null === $account = AccountBalanceModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->find()){
            $account = new AccountBalanceModel();
            $account->shop_id = $this->request->shopId;
            $account->account_money = sprintf("%.2f",0);
            $account->spare_money = sprintf("%.2f",0);
            $account->lock_money = sprintf("%.2f",0);
            $account->save();
        }
        $shop_money = $type==1?$account->account_money:$account->lock_money;
        if($money>$shop_money){
            return $this->error('提现金额不能大于余额');
        }
        Db::startTrans();

        try{
            $config = DataConfigModel::where('1=1')->find();
            $withdraw = new WithdrawModel();
            $withdraw->shop_id = $this->request->shopId;
            $withdraw->withdraw_account_id = $withdraw_account_id;
            $withdraw->money = $money;
            $withdraw->before_money = $type==1?$account->account_money:$account->lock_money;
            $withdraw->after_money = $type==1?$account->account_money - $money:$account->lock_money - $money;
            $withdraw->status = 0;
            $withdraw->type = $type;
            if($config){
                $withdraw->fee_ratio = $type==2?$config->lock_settle_ratio:$config->settle_ratio;
                $withdraw->fee = $money*($withdraw->fee_ratio/100);
            }
            $withdraw->save();

            if($type==1){
                $account->account_money = $account->account_money - $money;
            }else{
                $account->lock_money = $account->lock_money - $money;
            }
            $account->save();

            $log = new WithdrawAccountLogModel();
            $data['shop_id'] = $this->request->shopId;
            $data['account_balance_id'] = $account['account_balance_id'];
            $data['type'] = -1;
            $data['info'] = '提现扣除';
            $data['type_id'] = 1;
            $data['balance'] = $money;
            $data['withdraw_id'] = $withdraw->withdraw_id;
            $data['log_type'] = $type;
            $log->save($data);

            //添加账户明细
            $sb_log['shop_id'] = $this->request->shopId;
            $sb_log['withdraw_id'] = $withdraw->withdraw_id;
            $sb_log['operate_id'] = $this->request->accountId;
            $sb_log['type'] = -1;
            $sb_log['balance'] = $money;
            $sb_log['before_balance'] = $withdraw->before_money;
            $sb_log['after_balance'] = $withdraw->after_money;
            $sb_log['from_type'] = 0;
            $sb_log['balance_type'] = 4;
            $sb_log['status'] = 0;
            $sb_log['operate_type'] = 0;
            $sb_log['add_time'] = date('Y-m-d H:i:s');
            $sb_log['edit_time'] = date('Y-m-d H:i:s');
            $sb_log['add_ip'] = request()->ip();
            ShopBalanceLogsModel::insertGetId($sb_log);

            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('操作成功');
   }
    /*提现账户管理*/
    public function withdrawAccountList(){
        $where=[

            ['is_delete','=',0],

            ['shop_id','=',$this->request->shopId]

        ];
        $withdraw_account_model = new WithdrawAccountModel();

        $order = ['is_default'=>'asc'];

        $field = "*";

        $append = [];

        $return=DataLogic::getDataList($withdraw_account_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);

    }
    /*获取提现账户*/
    public function withdrawAccount(){
        $withdraw_account_id = $this->request->param('withdraw_account_id/d',0);
        if(null === $withdraw_account = WithdrawAccountModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'withdraw_account_id'=>$withdraw_account_id])->find()){
            return $this->error('提现账户不存在');
        }
        return $this->success($withdraw_account);

    }
    /*提现账户新增/修改*/
    public function saveWithdrawAccount(){
        $type = $this->request->param('type/d',1);//1银行账户2支付宝账户
        $withdraw_account_id = $this->request->param('withdraw_account_id/d',0);
        $open_bank_name = $this->request->param('open_bank_name');
        $open_branch = $this->request->param('open_branch');
        $account_name = $this->request->param('account_name');
        $account_number = $this->request->param('account_number');
        $empower_book_img = $this->request->param('empower_book_img');

        if($type ==1 && empty($open_bank_name)) return $this->error('开户行不能为空');
        if($type ==1 && empty($open_branch)) return $this->error('开户支行不能为空');
        if(empty($account_name)) return $this->error('户名不能为空');
        if(empty($account_number)) return $this->error('账号不能为空');

        if($withdraw_account_id>0){
            if(null === $withdraw_account = WithdrawAccountModel::where(['type'=>$type,'shop_id'=>$this->request->shopId,'is_delete'=>0,'withdraw_account_id'=>$withdraw_account_id])->find()){
                return $this->error('提现账户不存在');
            }
        }else{
            $withdraw_account = new WithdrawAccountModel();
            $withdraw_account->shop_id = $this->request->shopId;
        }

        $withdraw_account->open_bank_name = $open_bank_name;
        $withdraw_account->open_branch = $open_branch;
        $withdraw_account->account_name = $account_name;
        $withdraw_account->account_number = $account_number;
        $withdraw_account->empower_book_img = $empower_book_img;
        $withdraw_account->type = $type;
        $withdraw_account->save();
        return $this->success('保存成功');
    }
    /*提现账户默认状态*/
    public function saveWithdrawAccountDefault(){
        $withdraw_account_id = $this->request->param('withdraw_account_id/d',0);
        if(null === $withdraw_account = WithdrawAccountModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'withdraw_account_id'=>$withdraw_account_id])->find()){
            return $this->error('提现账户不存在');
        }
        Db::startTrans();

        try{
            WithdrawAccountModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->save(['is_default'=>0]);

            WithdrawAccountModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'withdraw_account_id'=>$withdraw_account_id])->save(['is_default'=>1]);
            
            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('保存成功');
    }
    /*提现明细*/
    public function detail(){
        $type = $this->request->param('type/d',1);//1账户提现2分佣提现
        $year = $this->request->param('year/d',date('Y'));
        $month = $this->request->param('month/d',date('m'));

        $start_time =mktime(0,0,0,$month,1,$year);
        $end_time = mktime(23,59,59,($month+1),0,$year);

        $where['status'] = 1;
        $where['type'] = $type;
        $where['shop_id'] = $this->request->shopId;
        $where['start_time'] = date('Y-m-d H:i:s',$start_time);
        $where['end_time'] = date('Y-m-d H:i:s',$end_time);

        $order = ['add_time'=>'desc'];

        $return = WithdrawModel::list($where,$order,$this->request->page,$this->request->limit);

        return $this->success($return);

    }

    /*账户明细*/
    public function balanceDetail(){
        $year = $this->request->param('year/d',date('Y'));
        $month = $this->request->param('month/d',date('m'));

        $start_time =mktime(0,0,0,$month,1,$year);
        $end_time = mktime(23,59,59,($month+1),0,$year);

        $where['status'] = 1;
        $where['shop_id'] = $this->request->shopId;
        $where['start_time'] = date('Y-m-d H:i:s',$start_time);
        $where['end_time'] = date('Y-m-d H:i:s',$end_time);
        $where['balance_type'] = [2,3,4];
        $return = ShopBalanceLogsModel::dlist($where,'',$this->request->page,$this->request->limit);

        $b_where[] = ['shop_id','=',$this->request->shopId];
        $b_where[] = ['add_time','>=',$where['start_time']];
        $b_where[] = ['add_time','<=',$where['end_time']];
        $b_where[] = ['status','=',1];
        $b_where[] = ['balance_type','in', [2,3,4]];
        //入账
        $return['in_count'] = ShopBalanceLogsModel::where($b_where)->where(['type'=>1])->count();
        $in_money = ShopBalanceLogsModel::where($b_where)->where(['type'=>1])->sum('balance');
        //支出
        $return['out_count'] = ShopBalanceLogsModel::where($b_where)->where(['type'=>-1])->count();
        $out_money = ShopBalanceLogsModel::where($b_where)->where(['type'=>-1])->sum('balance');
        //账户余额
        $account = AccountBalanceModel::getById(['shop_id'=>$this->request->shopId,'is_delete'=>0]);
        $return['account_money'] = $account['account_money'];
        $return['in_money'] = sprintf("%.2f",$in_money);
        $return['out_money'] = sprintf("%.2f",$out_money);
        return $this->success($return);

    }

}